<template>
  <div class="stations-table">
    <div class="table-header">
      <h3 class="table-title">{{ title || '表格数据' }}</h3>
      <span class="total-count">共 {{ tableData.length }} 条数据</span>
    </div>

    <!-- 保留element-plus滚动条组件，恢复原有美化样式 -->
    <el-scrollbar class="table-scroll" wrap-class="scrollbar-wrap">
      <div class="table-container">
        <!-- 表头 -->
        <div class="table-row header-row">
          <div 
            v-for="(col, index) in columns" 
            :key="col.prop" 
            class="table-cell header-cell"
            :style="getColumnStyle(index)"
          >
            {{ col.label }}
          </div>
        </div>

        <!-- 表体 -->
        <div v-if="tableData.length === 0" class="empty-row">
          <div class="empty-cell" :style="{ width: `calc(100% - 20px)` }">
            暂无数据
          </div>
        </div>

        <div 
          v-else
          v-for="(row, rowIdx) in tableData" 
          :key="row.id || rowIdx"
          class="table-row body-row"
        >
          <div 
            v-for="(col, colIdx) in columns" 
            :key="col.prop" 
            class="table-cell body-cell"
            :style="getColumnStyle(colIdx)"
          >
            <template v-if="slots[col.prop]">
              <slot :name="col.prop" :row="row" :index="rowIdx" />
            </template>
            <template v-else-if="col.render">
              <span class="content-text">{{ col.render(row) }}</span>
            </template>
            <template v-else>
              <span class="content-text">{{ row[col.prop] || col.default || '-' }}</span>
            </template>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick, useSlots } from 'vue';
import { ElScrollbar } from 'element-plus'; // 恢复滚动条组件

const slots = useSlots();

// Props定义
const props = defineProps({
  title: { type: String, default: '' },
  columns: { 
    type: Array, 
    required: true,
    validator: cols => cols.every(col => col.prop && col.label)
  },
  data: { type: Array, default: () => [] },
  testData: { type: Array, default: () => [] }
});

// 核心数据
const tableData = ref([]);
const measureEl = ref(null);
const containerWidth = ref(0);
const adaptiveWidths = ref([]);

// 初始化
onMounted(() => {
  // 测量元素
  const el = document.createElement('span');
  Object.assign(el.style, {
    visibility: 'hidden',
    position: 'absolute',
    whiteSpace: 'nowrap',
    padding: '8px 10px',
    fontSize: '12px',
    fontFamily: 'Arial, sans-serif',
    top: '-1000px'
  });
  document.body.appendChild(el);
  measureEl.value = el;

  // 容器宽度监听
  const container = document.querySelector('.table-container');
  if (container) {
    containerWidth.value = container.offsetWidth;
    const observer = new ResizeObserver(entries => {
      containerWidth.value = entries[0].contentRect.width;
    });
    observer.observe(container);
  }

  updateData();
});

// 数据更新
const updateData = () => {
  // 优先使用data，只有当data为空时才使用testData
  if (props.data.length > 0) {
    tableData.value = [...props.data];
  } else if (props.testData.length > 0) {
    tableData.value = [...props.testData];
  } else {
    tableData.value = [];
  }
  calculateAdaptiveWidths();
};

// 文本宽度测量
const getTextWidth = (text) => {
  if (!measureEl.value) return 100;
  measureEl.value.textContent = String(text || '');
  return measureEl.value.offsetWidth;
};

// 自适应宽度计算
const calculateAdaptiveWidths = () => {
  const widths = [];
  props.columns.forEach((col, index) => {
    if (col.width === undefined || !isValidWidth(col.width)) {
      let maxWidth = getTextWidth(col.label);
      tableData.value.forEach(row => {
        const content = col.render 
          ? (col.render(row) || '') 
          : (row[col.prop] || col.default || '');
        maxWidth = Math.max(maxWidth, getTextWidth(content));
      });
      if (col.prop && slots[col.prop]) {
        maxWidth = Math.max(maxWidth, 200);
      }
      widths[index] = maxWidth;
    } else {
      widths[index] = 0;
    }
  });
  adaptiveWidths.value = widths;
};

// 宽度有效性判断
const isValidWidth = (width) => {
  if (typeof width === 'number') return true;
  if (typeof width === 'string') {
    return /^\d+px$/.test(width) || /^\d+%$/.test(width);
  }
  return false;
};

// 列样式
const getColumnStyle = (index) => {
  const col = props.columns[index];
  if (!col) return { width: '100px' };

  if (typeof col.width === 'string' && col.width.endsWith('%')) {
    return { width: col.width, minWidth: col.width };
  }

  if (col.width !== undefined && isValidWidth(col.width)) {
    const widthVal = typeof col.width === 'number' 
      ? `${col.width}px` 
      : col.width;
    return { width: widthVal, minWidth: widthVal };
  }

  return { 
    width: `${adaptiveWidths.value[index] || 100}px`,
    minWidth: `${adaptiveWidths.value[index] || 100}px`
  };
};

// 监听
watch(() => props.data, updateData, { deep: true });
watch(() => props.testData, () => {
  if (props.data.length === 0) { // 只有当data为空时才更新
    updateData();
  }
}, { deep: true });
watch(() => props.columns, calculateAdaptiveWidths, { deep: true, immediate: true });
watch(containerWidth, calculateAdaptiveWidths);

// 清理
onUnmounted(() => {
  if (measureEl.value) {
    document.body.removeChild(measureEl.value);
  }
});
</script>

<style scoped>
.stations-table {
  background: linear-gradient(145deg, #0c2a5f, #082252);
  border: 1px solid rgba(95, 158, 255, 0.3);
  border-radius: 6px;
  padding: 0 10px 10px;
  box-sizing: border-box;
  min-height: 300px;
  font-family: 'Arial, sans-serif';
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid rgba(95, 158, 255, 0.2);
  margin-bottom: 10px;
}

.table-title {
  font-size: 16px;
  color: #8ec5fc;
  margin: 0;
}

.total-count {
  font-size: 12px;
  color: #8ec5fc;
  padding: 3px 8px;
  background: rgba(15, 45, 100, 0.3);
  border-radius: 4px;
}

/* 恢复element-plus滚动条样式兼容 */
.table-scroll {
  flex: 1;
  overflow: auto;
  max-height: calc(100% - 50px);
}

/* 滚动条容器样式 */
.scrollbar-wrap {
  overflow-x: auto !important;
  overflow-y: hidden !important;
}

/* 美化滚动条（保持原有样式） */
:deep(.el-scrollbar__bar) {
  background-color: rgba(150, 150, 150, 0.2) !important;
}

:deep(.el-scrollbar__thumb) {
  background-color: rgba(100, 149, 237, 0.5) !important;
  border-radius: 4px !important;
}

:deep(.el-scrollbar__thumb:hover) {
  background-color: rgba(100, 149, 237, 0.8) !important;
}

.table-container {
  width: 100%;
  min-width: 800px;
}

.table-row {
  display: flex;
  width: 100%;
}

.table-cell {
  padding: 8px 10px;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header-cell {
  font-size: 12px;
  color: #8ec5fc;
  font-weight: 600;
  background: rgba(10, 36, 85, 0.9);
  border-bottom: 1px solid rgba(95, 158, 255, 0.3);
}

.body-cell {
  font-size: 12px;
  color: #e0f0ff;
  border-bottom: 1px solid rgba(95, 158, 255, 0.15);
}

.body-row:hover {
  background: rgba(100, 149, 237, 0.05);
}

.empty-row {
  padding: 20px 0;
}

.empty-cell {
  font-size: 12px;
  color: #8ec5fc;
  text-align: center;
  padding: 20px;
  background: rgba(10, 36, 85, 0.3);
  margin: 0 auto;
}
</style>